#include "basic.h"

int FILEAPI_GetFileSize(const char* pszFileName, OUT U64& u64Size)
{
    int iRet      = -1;
    FILE* pstFile = NULL;

    if(pszFileName == NULL) SET_RET_AND_GOTO_EXIT(COMMON_ERR_INVALIDARGS);

    pstFile = fopen(pszFileName, "rb");
    if(pstFile == NULL) SET_RET_AND_GOTO_EXIT(COMMON_ERR_FILE);

    fseek(pstFile, 0, SEEK_END);
    u64Size = ftell(pstFile);

    iRet = 0;
_Exit:
    if(pstFile) fclose(pstFile);
    return iRet;
}

int FILEAPI_ReadFile(const char* pszFileName, OUT STD_BUFFER& bufData)
{
    int iRet = -1;
    int iResult;
    FILE* pstFile = NULL;
    U64 u64Size;

    if(pszFileName == NULL) SET_RET_AND_GOTO_EXIT(COMMON_ERR_INVALIDARGS);

    iResult = FILEAPI_GetFileSize(pszFileName, u64Size);
    if(iResult < 0) SET_RET_AND_GOTO_EXIT(COMMON_ERR_FILE);
    if(u64Size > (1024 * 1024 * 1024)) SET_RET_AND_GOTO_EXIT(COMMON_ERR_NOMEM);

    pstFile = fopen(pszFileName, "rb");
    if(pstFile == NULL) SET_RET_AND_GOTO_EXIT(COMMON_ERR_FILE);

    bufData.resize(u64Size);
    iResult = fread(bufData.data(), u64Size, 1, pstFile);
    if(iResult != 1) SET_RET_AND_GOTO_EXIT(COMMON_ERR_FILE);

    iRet = 0;
_Exit:
    if(pstFile) fclose(pstFile);
    return iRet;
}

int FILEAPI_WriteFile(const char* pszFileName, const STD_BUFFER& bufData) { return FILEAPI_WriteFile(pszFileName, bufData.data(), bufData.size()); }

int FILEAPI_WriteFile(const char* pszFileName, const BYTE* data, int iLen)
{
    int iRet = -1;
    int iResult;
    FILE* pstFile = NULL;

    if(pszFileName == NULL) SET_RET_AND_GOTO_EXIT(COMMON_ERR_INVALIDARGS);

    pstFile = fopen(pszFileName, "wb");
    if(pstFile == NULL) SET_RET_AND_GOTO_EXIT(COMMON_ERR_FILE);

    iResult = fwrite(data, iLen, 1, pstFile);
    if(iResult != 1) SET_RET_AND_GOTO_EXIT(COMMON_ERR_FILE);

    iRet = 0;
_Exit:
    if(pstFile) fclose(pstFile);
    return iRet;
}
